use my_commons::*;

pub fn test_move() {
    let _s1 = 6; // 未使用
    let s1 = String::from("hello"); // shadow

    let (s1, len) = calculate_length(s1);
    println!("The length of  {s1} is {len}");
}

pub fn test_move2() {
    let s1 = String::from("hello"); // shadow

    let (mut s1, len) = calculate_length(s1);
    println!("The old length of  {s1} is {len}");

    change(&mut s1);

    let (s1, len) = calculate_length(s1);
    println!("The new length of  {s1} is {len}");
}

fn calculate_length(s: String) -> (String, usize) {
    let length = s.len();
    (s, length)
}

fn change(some_string: &mut String) {
    some_string.push_str(", World");
}

fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[..i];
        }
    }
    &s
}

//-----------------------------------------------
pub fn test_scope() {
    let mut x = 6;
    {
        x = 7;
    }
    println!("x is {x}");

    my_sep();
    let mut str = String::from("sss");
    {
        str.push_str("ttt");
    }
    println!("str is {str}");
}

pub fn test_str() {
    fn print_word(word: &str) {
        println!("1st word is {word}");
    }

    let my_string = String::from("hello1 world");
    let word = first_word(&my_string);
    print_word(word);

    let word = first_word(&my_string[..]);
    print_word(word);

    let my_string_literal = "hello2 world";

    let word = first_word(&my_string_literal[..]);
    print_word(word);

    let word = first_word(&my_string_literal);
    print_word(word);
}
